<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      th:replace="~{layout/base :: layout(~{::title}, ~{::section})}">
<head>
    <meta charset="UTF-8">
    <title>搜索结果 - 电子书下载平台</title>
</head>
<body>
    <section>
        <div class="container py-5">
            <div class="row">
                <!-- 左侧筛选面板 -->
                <div class="col-lg-3 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">筛选条件</h5>
                        </div>
                        <div class="card-body">
                            <form th:action="@{/search}" method="get" id="filterForm">
                                <!-- 保留原始关键词 -->
                                <input type="hidden" name="keyword" th:value="${param.keyword}" />
                                
                                <!-- 年份范围 -->
                                <div class="mb-3">
                                    <label class="form-label">出版年份</label>
                                    <div class="row g-2">
                                        <div class="col-6">
                                            <input type="number" class="form-control" name="yearFrom" placeholder="从" min="1800" max="2100"
                                                   th:value="${param.yearFrom}" />
                                        </div>
                                        <div class="col-6">
                                            <input type="number" class="form-control" name="yearTo" placeholder="至" min="1800" max="2100"
                                                   th:value="${param.yearTo}" />
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 语言 -->
                                <div class="mb-3">
                                    <label class="form-label">语言</label>
                                    <select class="form-select" name="language">
                                        <option value="">所有语言</option>
                                        <option value="简体中文" th:selected="${param.language != null && param.language[0] == '简体中文'}">简体中文</option>
                                        <option value="繁體中文" th:selected="${param.language != null && param.language[0] == '繁體中文'}">繁體中文</option>
                                        <option value="English" th:selected="${param.language != null && param.language[0] == 'English'}">English</option>
                                        <option value="日本語" th:selected="${param.language != null && param.language[0] == '日本語'}">日本語</option>
                                        <option value="한국어" th:selected="${param.language != null && param.language[0] == '한국어'}">한국어</option>
                                        <option value="Français" th:selected="${param.language != null && param.language[0] == 'Français'}">Français</option>
                                        <option value="Deutsch" th:selected="${param.language != null && param.language[0] == 'Deutsch'}">Deutsch</option>
                                        <option value="Español" th:selected="${param.language != null && param.language[0] == 'Español'}">Español</option>
                                        <option value="Русский" th:selected="${param.language != null && param.language[0] == 'Русский'}">Русский</option>
                                    </select>
                                </div>
                                
                                <!-- 文件格式 -->
                                <div class="mb-3">
                                    <label class="form-label">文件格式</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="format" value="PDF" id="formatPdf"
                                               th:checked="${param.format != null && #arrays.contains(param.format, 'PDF')}">
                                        <label class="form-check-label" for="formatPdf">PDF</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="format" value="EPUB" id="formatEpub"
                                               th:checked="${param.format != null && #arrays.contains(param.format, 'EPUB')}">
                                        <label class="form-check-label" for="formatEpub">EPUB</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="format" value="MOBI" id="formatMobi"
                                               th:checked="${param.format != null && #arrays.contains(param.format, 'MOBI')}">
                                        <label class="form-check-label" for="formatMobi">MOBI</label>
                                    </div>
                                </div>
                                
                                <!-- 分类 -->
                                <div class="mb-3">
                                    <label class="form-label">分类</label>
                                    <select class="form-select" name="category">
                                        <option value="">所有分类</option>
                                        <option th:each="category : ${categories}" 
                                                th:value="${category.id}" 
                                                th:text="${category.name}"
                                                th:selected="${param.category != null && param.category[0] == category.id}">分类名称</option>
                                        <!-- 静态示例 -->
                                        <option th:if="${categories == null || #lists.isEmpty(categories)}" value="1" th:selected="${param.category != null && param.category[0] == '1'}">文学</option>
                                        <option th:if="${categories == null || #lists.isEmpty(categories)}" value="2" th:selected="${param.category != null && param.category[0] == '2'}">科技</option>
                                        <option th:if="${categories == null || #lists.isEmpty(categories)}" value="3" th:selected="${param.category != null && param.category[0] == '3'}">教育考试</option>
                                        <option th:if="${categories == null || #lists.isEmpty(categories)}" value="4" th:selected="${param.category != null && param.category[0] == '4'}">经济管理</option>
                                        <option th:if="${categories == null || #lists.isEmpty(categories)}" value="5" th:selected="${param.category != null && param.category[0] == '5'}">计算机</option>
                                    </select>
                                </div>
                                
                                <!-- 按钮组 -->
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">应用筛选</button>
                                    <button type="button" class="btn btn-outline-secondary" id="resetFilter">重置筛选</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧搜索结果 -->
                <div class="col-lg-9">
                    <!-- 搜索结果头部 -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h4>
                            <span th:if="${param.keyword != null && !param.keyword.isEmpty()}">
                                "<span th:text="${param.keyword}">关键词</span>" 的搜索结果
                            </span>
                            <span th:unless="${param.keyword != null && !param.keyword.isEmpty()}">
                                所有书籍
                            </span>
                            <span class="badge bg-primary ms-2" th:text="${totalItems + ' 本'}">100 本</span>
                        </h4>
                        
                        <div class="d-flex align-items-center">
                            <span class="me-2">排序: </span>
                            <select class="form-select form-select-sm" id="sortSelect" name="sort">
                                <option value="relevance" th:selected="${param.sort == null || param.sort[0] == 'relevance'}">相关度</option>
                                <option value="popularity" th:selected="${param.sort != null && param.sort[0] == 'popularity'}">受欢迎度</option>
                                <option value="newest" th:selected="${param.sort != null && param.sort[0] == 'newest'}">最新上传</option>
                                <option value="oldest" th:selected="${param.sort != null && param.sort[0] == 'oldest'}">最早上传</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- 搜索结果列表 -->
                    <div class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-4" th:if="${books != null && !books.isEmpty()}">
                        <!-- 动态搜索结果 -->
                        <div class="col" th:each="book : ${books}">
                            <div class="card h-100">
                                <img th:src="${book.coverUrl != null ? book.coverUrl : '/img/default-cover.jpg'}" 
                                     class="card-img-top book-cover" alt="书籍封面">
                                <div class="card-body">
                                    <h5 class="card-title text-truncate">
                                        <a th:href="@{'/books/' + ${book.bookId}}" th:text="${book.title}"
                                           th:utext="${book.highlightedTitle != null ? book.highlightedTitle : book.title}">书籍标题</a>
                                    </h5>
                                    <p class="card-text mb-1">
                                        <small class="text-muted" th:text="${book.author}">作者名</small>
                                    </p>
                                    <p class="card-text text-truncate-2 mb-2"
                                       th:text="${book.description}"
                                       th:utext="${book.highlightedDescription != null ? book.highlightedDescription : book.description}">
                                        书籍描述...
                                    </p>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <div class="rating">
                                            <i class="fas fa-star"></i>
                                            <span th:text="${book.rating}">4.5</span>
                                        </div>
                                        <span class="badge bg-primary" th:text="${book.downloadCount + ' 次下载'}">1200 次下载</span>
                                    </div>
                                    <div>
                                        <span th:each="format : ${book.availableFormats}" class="badge me-1"
                                              th:classappend="${format == 'PDF' ? 'bg-danger' : (format == 'EPUB' ? 'bg-primary' : 'bg-success')}"
                                              th:text="${format}">PDF</span>
                                    </div>
                                </div>
                                <div class="card-footer d-grid">
                                    <a th:href="@{'/books/' + ${book.bookId}}" class="btn btn-sm btn-outline-primary">查看详情</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 搜索无结果 -->
                    <div class="card" th:if="${books == null || books.isEmpty()}">
                        <div class="card-body py-5 text-center">
                            <i class="fas fa-search fa-4x text-muted mb-3"></i>
                            <h5>未找到匹配结果</h5>
                            <p class="text-muted">尝试使用不同的关键词或减少筛选条件</p>
                            <a th:href="@{/search}" class="btn btn-outline-primary mt-2">查看所有书籍</a>
                        </div>
                    </div>
                    
                    <!-- 分页控件 -->
                    <nav aria-label="Page navigation" th:if="${totalPages > 1}">
                        <ul class="pagination justify-content-center mt-4">
                            <li class="page-item" th:classappend="${currentPage == 1} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{${#httpServletRequest.requestURI}(keyword=${param.keyword}, yearFrom=${param.yearFrom}, yearTo=${param.yearTo}, language=${param.language}, format=${param.format}, category=${param.category}, sort=${param.sort}, page=1)}" aria-label="First">
                                    <span aria-hidden="true">&laquo;&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:classappend="${currentPage == 1} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{${#httpServletRequest.requestURI}(keyword=${param.keyword}, yearFrom=${param.yearFrom}, yearTo=${param.yearTo}, language=${param.language}, format=${param.format}, category=${param.category}, sort=${param.sort}, page=${currentPage - 1})}" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:each="i : ${#numbers.sequence(currentPage > 2 ? currentPage - 2 : 1, currentPage + 2 < totalPages ? currentPage + 2 : totalPages)}"
                                th:classappend="${i == currentPage} ? 'active' : ''">
                                <a class="page-link" th:href="@{${#httpServletRequest.requestURI}(keyword=${param.keyword}, yearFrom=${param.yearFrom}, yearTo=${param.yearTo}, language=${param.language}, format=${param.format}, category=${param.category}, sort=${param.sort}, page=${i})}" th:text="${i}">1</a>
                            </li>
                            <li class="page-item" th:classappend="${currentPage == totalPages} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{${#httpServletRequest.requestURI}(keyword=${param.keyword}, yearFrom=${param.yearFrom}, yearTo=${param.yearTo}, language=${param.language}, format=${param.format}, category=${param.category}, sort=${param.sort}, page=${currentPage + 1})}" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                            <li class="page-item" th:classappend="${currentPage == totalPages} ? 'disabled' : ''">
                                <a class="page-link" th:href="@{${#httpServletRequest.requestURI}(keyword=${param.keyword}, yearFrom=${param.yearFrom}, yearTo=${param.yearTo}, language=${param.language}, format=${param.format}, category=${param.category}, sort=${param.sort}, page=${totalPages})}" aria-label="Last">
                                    <span aria-hidden="true">&raquo;&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 排序选择变化时自动提交
        const sortSelect = document.getElementById('sortSelect');
        if (sortSelect) {
            sortSelect.addEventListener('change', function() {
                // 获取当前URL参数
                const urlParams = new URLSearchParams(window.location.search);
                
                // 设置新的排序参数
                urlParams.set('sort', this.value);
                
                // 重定向到新URL
                window.location.href = window.location.pathname + '?' + urlParams.toString();
            });
        }
        
        // 重置筛选
        const resetFilterBtn = document.getElementById('resetFilter');
        if (resetFilterBtn) {
            resetFilterBtn.addEventListener('click', function() {
                // 获取当前关键词和页码
                const urlParams = new URLSearchParams(window.location.search);
                const keyword = urlParams.get('keyword') || '';
                
                // 只保留关键词参数，重置其他筛选条件
                window.location.href = window.location.pathname + (keyword ? '?keyword=' + keyword : '');
            });
        }
        
        // 高亮搜索结果
        function highlightResults() {
            const urlParams = new URLSearchParams(window.location.search);
            const keyword = urlParams.get('keyword');
            
            if (!keyword) return;
            
            // 如果后端没有提供高亮，可以在前端实现
            // 注意：如果后端已经提供高亮（用th:utext渲染），则不需要此步骤
            /*
            document.querySelectorAll('.search-result-title, .search-result-description').forEach(element => {
                const text = element.textContent;
                if (text.toLowerCase().includes(keyword.toLowerCase())) {
                    const regex = new RegExp('(' + keyword + ')', 'gi');
                    element.innerHTML = text.replace(regex, '<span class="highlight">$1</span>');
                }
            });
            */
        }
        
        // 初始执行高亮
        highlightResults();
    });
    </script>
</body>
</html> 